//
//  RegViewController.m
//  IBaby
//
//  Created by ZengYuan on 14/11/17.
//  Copyright (c) 2014年 com.zhongwei. All rights reserved.
//

#import "VerifycodeViewController.h"
#import <SMS_SDK/SMSSDK.h>
//#import "SMS_SDK/CountryAndAreaCode.h"
#import "SetpasswdViewController.h"

@interface VerifycodeViewController ()

@end

@implementation VerifycodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    HorizonLine *line = [[HorizonLine alloc]initWithFrame:CGRectMake(0, 0, inputCoverView.frame.size.width, 1)];
    //    [inputCoverView addSubview:line];
    //    [line setLineColor:RGB(201, 199, 206)];
    //
    //    line = [[HorizonLine alloc]initWithFrame:CGRectMake(58, inputCoverView.frame.size.height/2, inputCoverView.frame.size.width, 1)];
    //    [inputCoverView addSubview:line];
    //    [line setLineColor:RGB(201, 199, 206)];
    //
    //
    //    line = [[HorizonLine alloc]initWithFrame:CGRectMake(0, inputCoverView.frame.size.height-1, inputCoverView.frame.size.width, 1)];
    //    [inputCoverView addSubview:line];
    //    [line setLineColor:RGB(201, 199, 206)];
    
    //    UIEdgeInsets insets = UIEdgeInsetsMake(0, 50, 0, 50);
    //    UIImage *streImage = [[UIImage imageNamed:@"redbtn_bk"] resizableImageWithCapInsets:insets];
    //    [nextBtn setBackgroundImage:streImage forState:UIControlStateNormal];
//    [nextBtn setBackgroundImage:[UIImage resizableImage:@"圆角矩形-3"] forState:UIControlStateNormal];
    nextBtn.titleLabel.font = LONGBTN_FONT;
    verifycodeLabel.text = [NSString stringWithFormat:@"验证码发送到%@", self.phone];
    coverView.layer.cornerRadius=5;
    
    machine = [TimeMachine sharedInstance];
    
    [self getActivateCode:nil];
    [activateCodeField becomeFirstResponder];
    voiceCodeBtn.layer.cornerRadius=5;
    voiceCodeBtn.hidden=YES;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
    self.titleLabel.text=@"获取验证码";
    //    self.navigationItem.title=@"获取验证码";
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(countDown) name:kTimeMachineCountingDownNotification object:nil];
    
    machine = [TimeMachine sharedInstance];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kTimeMachineCountingDownNotification object:nil];
}

//刷新倒数计时的描述
-(void)freshCountdownSeconds:(int)time{
    
    if (time==0) {
        NSMutableAttributedString*str=[[NSMutableAttributedString alloc] initWithString:@"重新发送验证码"];
        //设置字体颜色
        [str addAttribute:NSForegroundColorAttributeName value:RGB(0, 0, 0) range:NSMakeRange(0, str.length)];
        //设置字体
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, str.length)];
        
        //居中对齐
        NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment=NSTextAlignmentCenter;
        [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
        
        [getCodeTipLabel setAttributedText:str];
        
    }else{
        
        
        NSMutableAttributedString*str=[[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"接收短信大约需要%d秒", time]];
        
        //设置字体
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, str.length)];
        
        //居中对齐
        NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.alignment=NSTextAlignmentCenter;
        [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
        
        
        //设置字体颜色
        [str addAttribute:NSForegroundColorAttributeName value:RGB(0, 0, 0) range:NSMakeRange(0, str.length)];
        
        //设置字体颜色
        [str addAttribute:NSForegroundColorAttributeName value:RGB(6, 134, 0) range:NSMakeRange(8, [NSString stringWithFormat:@"%d", time].length)];
        [getCodeTipLabel setAttributedText:str];
        
    }
    
}

-(void)countDown{
    [self freshCountdownSeconds:machine.countdownTime];
    //    [getActivateCodeBtn setTitle:[NSString stringWithFormat:@"%d", machine.countdownTime] forState:UIControlStateNormal];
    
    //倒计时结束
    if (machine.countdownTime == 0) {
        getActivateCodeBtn.userInteractionEnabled=YES;
//        voiceCodeBtn.hidden=NO;
        //        [self setActivateCodeBtnNormalState];
    }else{
        getActivateCodeBtn.userInteractionEnabled=NO;
        voiceCodeBtn.hidden=YES;
        
    }
}

//-(void)setActivateCodeBtnNormalState{
//    [getActivateCodeBtn setTitle:@"获取" forState:UIControlStateNormal];
//    [getActivateCodeBtn setTitleColor:RGB(82, 82, 82) forState:UIControlStateNormal];



//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

-(IBAction)getActivateCode:(id)sender{
    if ([self.phone length] == 0) {
        return;
    }
    NSString* rule1 = @"^1(3|5|7|8|4)\\d{9}";
    NSPredicate* pred=[NSPredicate predicateWithFormat:@"SELF MATCHES %@",rule1];
    BOOL isMatch=[pred evaluateWithObject:self.phone];
    if(isMatch){
        
        UIWindow *window=[[UIApplication sharedApplication].windows lastObject];
        hud=[MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.labelText=@"验证码下发中";
        
        
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS
                                 phoneNumber:self.phone  zone:@"86" customIdentifier:nil
                                            result:^(NSError *error) {
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    if (error == nil) {
                                                        hud.mode=MBProgressHUDModeText;
                                                        hud.labelText=@"验证码发送成功";
                                                        [hud hide:YES afterDelay:0.5];
                                                        if (!machine.isCounting) {
                                                            [machine startTimer:30];
                                                        }
                                                    }else{
                                                        hud.mode=MBProgressHUDModeText;
                                                        hud.labelText=@"验证码发送失败";
                                                        [hud hide:YES afterDelay:0.5];
                                                        
                                                        getActivateCodeBtn.userInteractionEnabled=YES;
//                                                        voiceCodeBtn.hidden=NO;
                                                        
                                                    }
                                                    
                                                });
                                                
                                            }];
    }
    
    
    
}

-(IBAction)getVoiceActivateCode:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确定发送" message:@"确定后将致电您的手机号，语音播报验证码。如不希望被来电打扰请使用短信验证码。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag=888;
    [alert show];
    
}




-(void)verify{
    
    [self.view endEditing:YES];
    
//        //设置密码
//        [self activate];
//        return;
    ////$
    
    if ([activateCodeField.text length] != 4) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"验证码至少4位" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        return;
    }
    
    [SMSSDK commitVerificationCode:activateCodeField.text
                       phoneNumber:self.phone
                            zone:@"86"
                            result:^(NSError *error) {
        if (!error) {
            NSLog(@"block 验证成功");
            
            //stop timer
            [machine stopTimer];
            //refresh count down
            [self freshCountdownSeconds:0];
            getActivateCodeBtn.userInteractionEnabled=YES;
            
            //设置密码
            [self activate];
        }else{
            NSLog(@"block 验证失败");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"验证码不对" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }];
    
}

-(void)activate{
    
    UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SetpasswdViewController *acvc = [board instantiateViewControllerWithIdentifier:@"acvc"];
    [self.navigationController pushViewController:acvc animated:YES];
    acvc.phone=self.phone;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(IBAction)goNext:(id)sender{
    [self verify];
}

-(void )navLeftAction{
    UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"验证码短信可能略有延迟，确定返回并重新开始吗" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消",@"返回", nil];
    [alertview show];
    alertview.tag=1000;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==1000 && buttonIndex==1) {
        [self.navigationController popViewControllerAnimated:YES];
    }    if (alertView.tag==888 && buttonIndex==1) {
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodVoice
                                phoneNumber:self.phone
                                            zone:@"86"
                           customIdentifier:nil result:^(NSError *error) {
                                                      if (!error)
                                                      {
                                                      }else{
                                                          MBALERT(@"语音验证码发送失败");
                                                      }
                                                      
                                                  }];
    }
}


@end
